var modSample_locLang=new localLang("modSample");
var modSample = new Class({
	Extends:WFWindow,
	sampleProxyEnable: true,
    maxTimerCounter: 0,  // any count number, 0: no timer, -1: not stop timer
    options: {
        name: 'modSample',
        title: modSample_locLang.label('title'),
        btnSettings: true,
        btnRefresh: true,
        btnHelp: true,
        btnMaximize:true,
        showRefreshInMaximizeScreen: true,
        btnClose: true,
        btnTimer: true,
        loadCSS: true,
        serverSetting: true,
		supportServerTypes:['modSimple'],
        defaultWidgetHeight: 244        
    },
    objTimerConfig: {
    	defaultConfig: {
    		timerUnit: ['seconds','minutes','hours','days'],
    		timerUnitInterval:{
    			seconds : ['5','60','120','180'],
    			minutes : ['1','2','3'],
                hours : ['12','24'],
                days : ['1','3','5']
    		},
	        timerOnDefaultSelected: '1',
    		timerUnitDefaultSelected: 'seconds',
    		timerUnitIntervalDefaultSelected: '5'
    	}
    },
    includeScript: ['a.js','b.js'],
    settingModalOption:{
        title: modSample_locLang.label('edit') + ' - '+ modSample_locLang.label('title'),
        content: '<input type="button" class="cancel" value="'+modSample_locLang.label('btn_cancel')+'">',
        callBack: function(){
            $$('.modalContent .cancel').addEvent('click',function(e){
                this.refreshMod();
                this.settingModal.close();
            }.bind(this));
        }
    },
    timerCallback: function() {
		var data = "module=modSimple&serverid=1&url="+encodeURIComponent(this.widgetPath+'/timerLog.php?act=render&id=' + this.id)+ '&pool_id=TimerLog'+this.id;
        this.proxyRequest(data,function(){},function(){});
    },
    maximizeModalOption: {
        mainContent: '',
        bottomContent: '<div id="close_maximizeScreen" class="ui-button close clearfix"><div class="left"></div><div class="mid">'+lang.label('close')+'</div></div>',
        callBack: function(){
            this.maximizeChartBox = new Element('div', {'class':'container'}).injectInside($$('#widgetMaximizeScreen .hd')[0]);
            this.displayMaximizeChart();

            $$('.modalContent .close').addEvent('click',function(e){
                this.maximizeModal.close();
            }.bind(this));

            $$('.modalTitle .refresh').addEvent('click',function(e){
                if(this.myMaximizeChart && this.myMaximizeChart.destroy){
                    this.myMaximizeChart.destroy();
                    this.myMaximizeChart = null;
                    if (typeof(CollectGarbage) === 'function'){
                        CollectGarbage();
                    }
                }
                this.displayMaximizeChart();
            }.bind(this));
        },
        callBackBeforeClose: function(){
            if(this.myMaximizeChart && this.myMaximizeChart.destroy){
                this.myMaximizeChart.destroy();
                this.myMaximizeChart = null;
                if (typeof(CollectGarbage) === 'function'){
                    CollectGarbage();
                }
            }
        },
        callBackAfterResize: function(){
            if(this.myMaximizeChart){
                this.myMaximizeChart.setSize($$('#widgetMaximizeScreen .hd')[0].getSize().x-20, $$('#widgetMaximizeScreen .hd')[0].getStyle('height').toInt()-20, false);
            }
        }
    },
    renderContent: function(){
    
        this.errormsg = new Element('div',{'class':'error'}).inject(this.boxBD);
        this.msg = new WFMessage(this.errormsg);
        var option = {
            type: '0', //0: error, 1: warn, 2: info
            description: 'aaa', //text
            button: 'aaa', //string
            callback: function(){alert('1');}, //callback function
            close: true //true or false      
        };
        var option2 = {
            type: '1', //0: error, 1: warn, 2: info
            description: 'bbb', //text
            button: 'bbb', //string
            callback: function(){alert('2');}, //callback function
            close: true //true or false        
        };
        //this.msg.fireEvent('message',option);
        //this.msg.fireEvent('message',option2);
        //this.addButton('btn_refresh',this.onClickRefresh2.bind(this));
        //this.fillTitle('title');
        // >>>>>>> Highcharts Step 1 : create a div dom element for Highcharts
        this.chartBox = new Element('div', {'class':'container'}).injectInside(this.boxBD);

        this.width = this.chartBox.getSize().x;
        this.height = 300;
        
        if(this.maxTimerCounter == 0){
            this.displayChart();
        }else{
            this.counter = 0;
            this.timer = this.displayChart.periodical(3000, this);
        }
    },
	onClickRefresh2: function(){
		var option = {
			title: 'customize button',
			content: '<input type="button" class="cancel" value="'+modSample_locLang.label('btn_cancel')+'">',
			callBack: function(){
				$$('.modalContent .cancel').addEvent('click',function(e){
					this.customButtonModal.close();
				}.bind(this));
			}.bind(this)
		};
		this.customButtonModal = new WFModal(option);
	},
    displayChart:function(){
        if(this.maxTimerCounter != 0){
            this.counter++;
            if(this.counter > 0 && this.counter == this.maxTimerCounter){
                clearInterval(this.timer);
            }
        }
        //var data = "module=modSimple&serverid="+encodeURIComponent('77,19,20')+"&url="+encodeURIComponent(this.widgetPath+'/sampleReporting.php?fakename=fake.xml');
		var data = "module=modSimple&serverid=1&url="+encodeURIComponent(this.widgetPath+'/sampleReporting.php?fakename=fake.json')+'&pool_id=displayChart'+this.id;
		if(this.sampleProxyEnable == true){
		    this.proxyRequest(data,this.displaySuccess.bind(this),this.displayFailure.bind(this));
        } else {
			this.displaySuccess();
        }
    },
    displayMaximizeChart:function(){
        var data = "module=modSimple&serverid=1&url="+encodeURIComponent(this.widgetPath+'/sampleReporting.php?fakename=maximize_screen_fake.json')+'&pool_id=displayMaximizeChart'+this.id;
        if(this.sampleProxyEnable == true){
            this.proxyRequest(data,this.displayMaximizeSuccess.bind(this),this.displayFailure.bind(this));
        } else {
            this.displayMaximizeSuccess();
        }
    },
    displaySuccess: function(response)
	{
    	// >>>>>>> Highcharts Step 2 : assume you get the highcharts json format data via request
        if(this.sampleProxyEnable == false )
		{
        	this.chart_data = [{
    			name: 'Tokyo',
    			data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
    		}, {
    			name: 'New York',
    			data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
    		}, {
    			name: 'Berlin',
    			data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
    		}, {
    			name: 'London',
    			data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
    		}];
        }else{
			this.chart_data = JSON.decode(response); 
        }
		
        this.renderChart(this.width, this.height);
        //fire when widget loaded or change height
        window.fireEvent('widget_load', this.widgetInfo);
    },
    displayMaximizeSuccess: function(response)
	{
    	// >>>>>>> Highcharts Step 2 : assume you get the highcharts json format data via request
        if(this.sampleProxyEnable == false )
		{
        	this.chart_data = [{
    			name: 'Tokyo',
    			data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
    		}, {
    			name: 'New York',
    			data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
    		}, {
    			name: 'Berlin',
    			data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
    		}, {
    			name: 'London',
    			data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
    		}];
        }else{
			this.chart_data = JSON.decode(response);
        }
        if($$('#widgetMaximizeScreen .hd') && $$('#widgetMaximizeScreen .hd')[0]){
            this.renderMaximizeChart($$('#widgetMaximizeScreen .hd')[0].getSize().x-20, $$('#widgetMaximizeScreen .hd')[0].getStyle('height').toInt()-20);
        }
    },
    displayFailure: function(){
    },
    onContentresize: function(event){
        if (this.myChart){
            var xy = this.getContentSize();
            this.myChart.setSize(xy.x, xy.y-this.errormsg.getSize().y, false);
        }
    },
    renderChart: function(x, y)
	{
        if(this.myChart && this.myChart.destroy){
            this.myChart.destroy();
            this.myChart = null;
            if (typeof(CollectGarbage) === 'function'){
                CollectGarbage();
            }
        }

		if(this.chart_data != null)
		{
			// >>>>>>> Highcharts Step 3 : define your chart json,
			// render chart will only create on the first load, 
			// after that any resize behavior will call refreshMod() API
			this.myChart = new Highcharts.Chart({
				
		         chart: {
		             renderTo: this.chartBox,
		             type: 'line',
		 			 width: x,
		 			 height: y
		 		  },
		 		  title: {
			    	text : ''
				  },
		 		  xAxis: {
		 			 categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
		 				'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	 				 labels: {
	 					 step: 2
    	             }
		 		  },
		 		  yAxis: {
		 			  title: {
		 				  text: 'Temperature (?°C)'
		 			  },
		 			  plotLines: [{
		 				  value: 0,
		 				  width: 1,
		 				  color: '#808080'
		 			  }]
		 		  },
		 		  tooltip: {
		 			  formatter: function() {
		 					  return '<b>'+ this.series.name +'</b><br/>'+
		 					  this.x +': '+ this.y +'?°C';
		 			  }
		 		  },
		          series: this.chart_data
		       });
		}
    },
    renderMaximizeChart: function(x, y)
	{
		if(this.chart_data != null)
		{
			// >>>>>>> Highcharts Step 3 : define your chart json,
			// render chart will only create on the first load,
			// after that any resize behavior will call refreshMod() API
			this.myMaximizeChart = new Highcharts.Chart({

		         chart: {
		             renderTo: this.maximizeChartBox,
		             type: 'line',
		 			 width: x,
		 			 height: y
		 		  },
		 		  title: {
				    	text : ''
		 		  },
		 		  xAxis: {
		 			 categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
		 				'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	 				 labels: {
		 					 step: 2
    	             }
		 		  },
		 		  yAxis: {
		 			  title: {
			 				  text: 'Temperature (?°C)'
		 			  },
		 			  plotLines: [{
		 				  value: 0,
		 				  width: 1,
		 				  color: '#808080'
		 			  }]
		 		  },
		 		  tooltip: {
		 			  formatter: function() {
		 					  return '<b>'+ this.series.name +'</b><br/>'+
			 					  this.x +': '+ this.y +'?°C';
		 			  }
		 		  },
		          series: this.chart_data
		       });
		}
    },
    // >>>>>>> Highcharts Step 4 : please follow below refreshMod implementation
    refreshMod:function()
	{
    	if (typeof(CollectGarbage) === 'function'){
			CollectGarbage();
		}
        if (this.sampleProxyEnable == true){
            var xy = this.getContentSize();
            this.width = xy.x;
            this.height = xy.y-this.errormsg.getSize().y;
            this.displayChart();
        } else {
            this.onContentresize();
        }
        //need to fire widget_load event if it change widget's height
        //window.fireEvent('widget_load');
    }
});
